﻿// Allows DOM elements to be dropped in this one during a drag and drop operation
define([
    'Wjs/ui/elements/managers/dragDropManager'
],
function () {
    'use strict';

    var dragDropManager = Wjs.getType('dragDropManager'),
        Draggable = Wjs.defineOnce({

            type: 'Draggable',

            internal: {

                construct: function (cfg, parent) {

                    cfg = cfg || {};

                    if (cfg.draggable || cfg.movable) {
                        this.setDraggable(cfg);
                    }
                }
            },

            setDraggable: function (cfg) {
                var me = this;

                cfg = cfg || {};

                me.onDragStart = cfg.onDragStart || me.onDragStart;
                me.onDrag = cfg.onDrag || me.onDrag;
                me.onDragEnd = cfg.onDragEnd || me.onDragEnd;

                // Add the draggable HTML5 attribute
                me.setAttributes({
                    draggable: true
                });

                me.addEvents({

                    dragstart: function (evt) {

                        // Set effectAllowed

                        if (me.onDragStart) {
                            me.onDragStart(evt);
                        }
                    },

                    drag: function (evt) {

                        if (me.onDrag) {
                            me.onDrag(evt);
                        }
                    },

                    dragend: function (evt) {

                        if (me.onDragEnd) {
                            me.onDragEnd(evt);
                        }
                    }
                });
            },

            onDragStart: function (evt) {

                // Get the top and left coordinates of the view
                var left = this.getLeft() - evt.clientX,
                    top = this.getTop() - evt.clientY;

                dragDropManager.add(this); // Add the view to the manager

                evt.dataTransfer.setData('text/plain', left + ',' + top);
            },
        });

    return Draggable;
});